package indi.mozping.lockp.rwl;

import indi.mozping.tools.SleepTools;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author by mozping
 * @Classname ReadWriteLockTest
 * @Description TODO
 * @Date 2019/1/2 20:07
 */
public class ReadWriteLockTest {

    private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock writeLock = readWriteLock.writeLock();
    private static Lock readLock = readWriteLock.readLock();

    public static void main(String[] args) {

        System.out.println("测试写锁---------------------------------");
        for (int i = 1; i <= 3; i++) {
            new MyWriteThread().start();
        }
        SleepTools.second(10);

        System.out.println("测试读锁---------------------------------");
        for (int i = 1; i <= 3; i++) {
            new MyReadThread().start();
        }
    }

    private static class MyWriteThread extends Thread {
        @Override
        public void run() {
            writeLock.lock();
            System.out.println("[" + Thread.currentThread().getName() + "] 拿到锁了，做点事情....");
            SleepTools.randomMs(3000);
            System.out.println("[" + Thread.currentThread().getName() + "] 做完了....");
            writeLock.unlock();
        }
    }

    private static class MyReadThread extends Thread {
        @Override
        public void run() {
            readLock.lock();
            System.out.println("[" + Thread.currentThread().getName() + "] 拿到锁了，做点事情....");
            SleepTools.randomMs(3000);
            System.out.println("[" + Thread.currentThread().getName() + "] 做完了....");
            readLock.unlock();
        }
    }

}
